package com.hdmp.wework.service;

import com.hdmp.wework.entity.GryxWechatGzyhEntity;
import com.hdmp.wework.entity.GryxWechatTokenEntity;
import com.hdmp.wework.mapper.WechatGzyhMapper;
import com.hdmp.wework.mapper.WechatTokenMapper;
import com.hdmp.wework.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.api.impl.WxMpUserServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WeixinTokenService {

    @Autowired
    WeixinService weixinService;
    @Autowired
    WechatTokenMapper tokenMapper;
    @Autowired
    WechatGzyhMapper gzyhMapper;

    @Transactional
    public void updateToken(){
        List<GryxWechatTokenEntity> list = tokenMapper.queryAll();
        for(GryxWechatTokenEntity entity : list){
            Long currentTime = new Date().getTime();
            //时间超过60分钟，刷新token
            if(currentTime - entity.getTimeVersion() >= 60*60*1000){
                WxMpService wxMpService =  weixinService.getMpServices().get(entity.getAppid());
                String token = "";String ticket = "";
                try{
                    token = wxMpService.getAccessToken();
                    ticket = wxMpService.getJsapiTicket();
                    entity.setToken(token);
                    entity.setTicket(ticket);
                    entity.setTimeVersion(currentTime);
                    tokenMapper.updateById(entity);
                }catch (Exception e){
                    log.error(e.getMessage());
                }
            }else{
                log.info("未到更新时间，无需更新");
            }
        }
    }
    //根据appId获取token
    public String getToken(String appId){
        GryxWechatTokenEntity entity = tokenMapper.queryTokenByAppid(appId);
        Long currentTime = new Date().getTime();
        //时间超过60分钟，刷新token
        if(currentTime - entity.getTimeVersion() >= 60*60*1000){
            WxMpService wxMpService =  weixinService.getMpServices().get(entity.getAppid());
            String token = "";String ticket = "";
            try{
                token = wxMpService.getAccessToken();
                ticket = wxMpService.getJsapiTicket();
                entity.setTicket(ticket);
                entity.setToken(token);
                entity.setTimeVersion(currentTime);
                tokenMapper.updateById(entity);
            }catch (Exception e){
                log.error(e.getMessage());
                log.error("获取token失败");
            }
        }else{
            log.info("未到更新时间，无需更新");
        }
        return entity.getToken();
    }

    //根据appId获取token
    public String getTicket(GryxWechatTokenEntity entity){
        Long currentTime = new Date().getTime();
        //时间超过60分钟，刷新token
        if(currentTime - entity.getTimeVersion() >= 60*60*1000){
            WxMpService wxMpService =  weixinService.getMpServices().get(entity.getAppid());
            String token = "";String ticket = "";
            try{
                token = wxMpService.getAccessToken();
                ticket = wxMpService.getJsapiTicket();
                entity.setTicket(ticket);
                entity.setToken(token);
                entity.setTimeVersion(currentTime);
                tokenMapper.updateById(entity);
                System.out.println();
            }catch (Exception e){
                log.error(e.getMessage());
                log.error("获取ticket失败");
            }
        }else{
            log.info("未到更新时间，无需更新");
        }
        return entity.getTicket();
    }

    //根据appid和code获取openid
    public String getOpenId(String appId, String code){
        WxMpService wxMpService =  weixinService.getMpServices().get(appId);
        String openId = "";
        try{
            WxMpOAuth2AccessToken oAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            openId = oAuth2AccessToken.getOpenId();
            System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^");
            System.out.println(oAuth2AccessToken);
            System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^");
            System.out.println(openId);
            System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^");
            if(openId != null){
                GryxWechatGzyhEntity gzyhEntity = gzyhMapper.queryByOpenIdAndIsdel(openId);
                if(gzyhEntity == null){
                    //已关注但是未保存
                    WxMpUser user = wxMpService.getUserService().userInfo( openId);
                    gzyhEntity = new GryxWechatGzyhEntity();
                    gzyhEntity.setAppid(appId);
                    gzyhEntity.setOpenid(openId);
                    gzyhEntity.setSubscribe(user.getSubscribe());
                    gzyhEntity.setSubscribetime(new Date(user.getSubscribeTime()));
                    gzyhEntity.setNickname(user.getNickname());
                    gzyhEntity.setSex(user.getSexDesc());
                    gzyhEntity.setCountry(user.getCountry());
                    gzyhEntity.setProvince(user.getProvince());
                    gzyhEntity.setCity(user.getCity());
                    gzyhEntity.setHeadimgurl(user.getHeadImgUrl());
                    gzyhEntity.setIsdel("0");
                    gzyhEntity.setCreateDate(new Date());
                    gzyhEntity.setUpdateDate(new Date());
                    gzyhMapper.insert(gzyhEntity);
                }
            }
            return openId;
        }catch (WxErrorException e){
            e.printStackTrace();
            log.error("获取OPENID失败"+e);
            return "";
        }finally {
            log.error("^^^^^^^^^^^^^^^^^^^^^^^^^");
            log.error(openId);
            log.error("^^^^^^^^^^^^^^^^^^^^^^^^^");
            return openId;
        }
    }

    //获取jssdk
    public Map<String ,String> getJssdk(String appId, String url){
        GryxWechatTokenEntity entity = tokenMapper.queryTokenByAppid(appId);
        String timestamp = Long.toString(System.currentTimeMillis()/1000);
        String nonceStr = RandomUtil.generateString(15);
        String string1 = "jsapi_ticket="+getTicket(entity)+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url=" + url;
        String signature = "";
        //签名
        try{
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = RandomUtil.byteToHex(crypt.digest());
        }
        catch (Exception e){
            log.error(e.getMessage(),e);
        }
        //结果集返回
        Map<String, String> map = new HashMap<>();
        map.put("appid",appId);
        map.put("timestamp",timestamp);
        map.put("nonceStr",nonceStr);
        map.put("signature",signature);
        map.put("jsapi_ticket",entity.getTicket());
        map.put("url",url);
        System.out.println("#######################");
        System.out.println("map::==>>"+map);
        return map;
    }

}